package com.gaattc.controller.admin;

import com.gaattc.model.Result;
import com.gaattc.model.User;
import com.gaattc.service.UserService;
import com.gaattc.service.UserServiceImpl;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/api/admin/user/*")
public class UserServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    private Gson gson = new Gson();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取请求URI
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/admin/user/", "");
        //分发处理请求
        if("allUser".equals(action)) {
            allUser(request, response);
        } else if("deleteUser".equals(action)) {
            deleteUser(request, response);
        } else if("searchUser".equals(action)) {
            searchUser(request, response);
        }
    }

    /**
     * 查询用户
     * @param request req
     * @param response resp
     */
    private void searchUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String word = request.getParameter("word");
        List<User> list = userService.searchUser(word);
        response.getWriter().println(gson.toJson(Result.ok(list)));
    }

    /**
     * 删除用户
     * @param request req
     * @param response resp
     * @throws IOException io
     */
    private void deleteUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        int code = userService.deleteUser(id);
        if(code == 1) {
            response.getWriter().println(gson.toJson(Result.ok()));
            return;
        }
        response.getWriter().println(gson.toJson(Result.error("删除失败")));
    }

    /**
     * 获取所有用户信息
     * @param request req
     * @param response resp
     * @throws IOException io
     */
    private void allUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<User> list = userService.allUser();
        response.getWriter().println(gson.toJson(Result.ok(list)));
    }
}
